//------AJAX---------
function getPagePart(url, elementSelector) {
	$.ajax({
		url : url,
		async : false, //to avoid page jumping
		success : function(response) {
			$(elementSelector).html(response);
		}
	});
}

// ------dynamic section update---------
function setSection(newUrl) {
	window.History.pushState(null, null, newUrl);
}
function setHistoryStateChangeListener() {
	window.History.Adapter.bind(window, 'statechange', function() {
		setSectionCallBack(window.History.getState());
	});
}
function setSectionCallBack(historyState) {
	var urlParameter = location.search.split('?')[1];
	var pagePartUrl = '';
	if (!urlParameter || urlParameter == 'dress' || urlParameter == 'tshirt') {
		pagePartUrl = 'parts/gallery.html';
	} else if (urlParameter == 'info' || urlParameter == 'contacts' 
		|| urlParameter == 'video') { 
		pagePartUrl = 'parts/' + urlParameter + '.html';
	} else { // for any single item
		pagePartUrl = 'parts/item.html';
	}
	getPagePart(pagePartUrl, '#main');
	runScript(); // calls script in loaded part
}

// ------csv processing---------
function csvFileToObjects(fileUrl) {
	$.ajax({
		url : fileUrl,
		async : false,
		cache: false,
		success : function(csvString) {
			items = $.csv.toObjects(csvString);
		}
	});
}
function getAllItems(fileUrl) {
	csvFileToObjects(fileUrl);
	return items;
}

function getItemByModel(fileUrl, model) {
	var allItems = getAllItems(fileUrl);
	for (var i = 0; i < allItems.length; i++) {
		if (allItems[i].model == model) {
			return allItems[i];
		}
	}
	return null;
}

function getItemsByType(fileUrl, typeEn) {
	var allItems = getAllItems(fileUrl);
	var selectedItems = new Array();
	for (var i = 0; i < allItems.length; i++) {
		if (allItems[i].typeEn == typeEn) {
			selectedItems.push(allItems[i]);
		}
	}
	return selectedItems;
}

function filterItemsByPrice(items, minPrice, maxPrice) {
	var selectedItems = new Array();
	for (var i = 0; i < items.length; i++) {
		var item = items[i];
		if (+item.price >= +minPrice && +item.price <= +maxPrice) {
			selectedItems.push(item);
		}
	}
	return selectedItems;
}	

//------misc---------
function shuffleArray(o) { //taken from http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array-in-javascript
	for ( var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

